import axios from 'axios'
import { ElLoading } from 'element-plus'
// import config from '../config'
import notification from './notification'
import router from '../router'
import useToken from './../stores/token.js'

const baseURL = 'http://127.0.0.1:8080'

var loadingInstance = null

const service = axios.create({ baseURL })

service.interceptors.request.use(config => {
	loadingInstance = ElLoading.service()
	//TODO 每个请求都需要携带Token数据到后台，从pinia中获取
	const { token } = useToken()
	console.log('request.js', token)
	if (token) {
		// 请求头携带token数据
		config.headers.token = token
	}
	return config
})

service.interceptors.response.use(
	response => {
		loadingInstance.close()
		const { code, data, msg } = response.data
		if (code === 0) {
			if (msg !== '' && msg !== undefined) {
				notification({
					message: msg,
					type: 'success',
				})
			}
			return data || true
		}
		notification({
			message: msg,
			type: 'error',
		})
		if (code === 2) {
			router.push({ name: 'login' })
		}
		return false
	},
	error => {
		loadingInstance.close()
		notification({
			message: '请求失败',
			type: 'error',
		})
		console.log(error)
	}
)

export default service
